<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab" type="border-card">
			<el-tab-pane label="基础信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>基本信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_BillCode_FormItem"
										prop="Entity.BillCode"
										:rules="[{ required: true, message: '单据编号为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据的唯一编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" disabled class="width100" placeholder="自动生成"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_Applicant_FormItem"
										prop="Entity.Applicant"
										:rules="[{ required: true, message: '申请人为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="申请人" tooltip="采购申请的发起人姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Applicant" disabled class="width100" placeholder="当前登录人"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_NeedDate_FormItem"
										prop="Entity.NeedDate"
										:rules="[{ required: true, message: '需求日期为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="需求日期" tooltip="物料的期望到货日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.NeedDate" disabled class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>采购信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="8" class="mb20">
									<el-form-item
										ref="Entity_PurchaseType_FormItem"
										prop="Entity.PurchaseType"
										:rules="[{ required: true, message: '采购类型为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="采购类型" tooltip="采购类型：常规、备用、设备新增、安全新增等" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.PurchaseType" disabled class="width100">
											<el-option key="常规" value="常规" label="常规"></el-option>
											<el-option key="设备新增" value="设备新增" label="设备新增"></el-option>
											<el-option key="安全新增" value="安全新增" label="安全新增"></el-option>
											<el-option key="其他" value="其他" label="其他"></el-option
										></el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="8" class="mb20">
									<el-form-item
										ref="Entity_MaterialType_FormItem"
										prop="Entity.MaterialType"
										:rules="[{ required: true, message: '物料类型为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="物料类型" tooltip="采购物料的分类" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.MaterialType" disabled class="width100">
											<el-option key="备品备件" value="备品备件" label="备品备件"></el-option>
											<el-option key="化工小料" value="化工小料" label="化工小料"></el-option>
											<el-option key="大宗原材料" value="大宗原材料" label="大宗原材料"></el-option
										></el-select>
									</el-form-item>
								</el-col>
								<!-- <el-col :xs="24" :lg="8" class="mb20">
									<el-form-item
										ref="Entity_PurchaseMethod_FormItem"
										prop="Entity.PurchaseMethod"
										:rules="[{ required: true, message: '采购方式为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="采购方式" tooltip="采购方式：集采、招标等" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.PurchaseMethod" disabled class="width100">
											<el-option key="集采" value="集采" label="集采"></el-option>
											<el-option key="招标" value="招标" label="招标"></el-option
										></el-select>
									</el-form-item>
								</el-col> -->
								<el-col :xs="24" :lg="8" class="mb20">
									<el-form-item
										ref="Entity_UrgencyLevel_FormItem"
										prop="Entity.UrgencyLevel"
										:rules="[{ required: true, message: '紧急程度为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="紧急程度" tooltip="采购的紧急程度：一般、紧急" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.UrgencyLevel" disabled class="width100">
											<el-option key="一般" value="一般" label="一般"></el-option>
											<el-option key="紧急" value="紧急" label="紧急"></el-option
										></el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20">
									<el-form-item ref="SelectedFilesIds_FormItem" prop="SelectedFilesIds">
										<template #label>
											<WtmLabelTooltip label="附件" tooltip="采购申请单关联的附件文件" />
										</template>
										<wtm-upload-file v-model="stateData.vmModel.SelectedFilesIds" disabled></wtm-upload-file>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.UrgencyLevel === '紧急'">
									<el-form-item ref="Entity_UrgencyReason_FormItem" prop="Entity.UrgencyReason">
										<template #label>
											<WtmLabelTooltip label="紧急采购原因" tooltip="紧急采购的详细说明和理由" />
										</template>
										<el-input
											v-model="stateData.vmModel.Entity.UrgencyReason"
											type="textarea"
											:rows="3"
											disabled
											placeholder="请输入紧急采购的详细说明和理由"
										></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>组织信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector
										v-model="stateData.vmModel.Entity.OrgId"
										label="所属公司"
										tooltip="采购申请单所属的公司"
										:auth="true"
										:disabled="true"
										:rules="[{ required: true, message: '所属公司为必填项', trigger: 'blur' }]"
									/>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector
										v-model="stateData.vmModel.Entity.GroupId"
										label="所属部门"
										tooltip="采购申请单所属的部门"
										:org-id="stateData.vmModel.Entity.OrgId"
										:auth="true"
										:disabled="true"
										:rules="[{ required: true, message: '所属部门为必填项', trigger: 'blur' }]"
									/>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>
			<el-tab-pane label="物料明细" name="materialentries" v-if="stateData.vmModel.Entity.ID">
				<SysPurchaseRequestBillEntryCopy :search-bar="false" :toolbar="false" :is-disabled="false" :bill-id="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
			<el-tab-pane label="审批信息" name="approval">
				<WtmWorkflowTimeline entityType="HengTong.Areas.SupplyChain.Controllers.SysPurchaseRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance, defineAsyncComponent } from 'vue';
import { SysPurchaseRequestBillApi as api } from '/@/views/supplychain/syspurchaserequestbill/api';
import other from '/@/utils/other';
import { ISysPurchaseRequestBillVm } from '/@/views/supplychain/syspurchaserequestbill/api/interface';
import { ISysSelectType, IViewModel } from '/@/types/common';

// 懒加载子组件
const SysPurchaseRequestBillEntryCopy = defineAsyncComponent(() => import('/@/views/supplychain/syspurchaserequestbillentry/indexCopy.vue'));
import ApproveReasonDialog from '/@/components/approveReason/index.vue';

const BILL_STATUS = {
	DRAFT: '草稿',
	IN_AUDIT: '审核中',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

const stateData = reactive<IViewModel<ISysPurchaseRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Applicant: null,
			RequestDate: null,
			NeedDate: null,
			PurchaseType: null,
			MaterialType: null,
			PurchaseMethod: null,
			UrgencyLevel: null,
			UrgencyReason: null,
			Amount: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			OrgId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			Files: null,
		},
		SelectedFilesIds: [],
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [] as ISysSelectType[],
	AllSysOrgs: [] as ISysSelectType[],
});

const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

const handleApiResponse = (response: any, isSubmit = false) => {
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
	}
	loading.value = false;
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 取消
const onClose = () => {
	closeDialog();
};

const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then((res) => handleApiResponse(res, true))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};
// 同意
const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};
// 拒绝
const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysPurchaseRequestBill/GetSysGroups', [], false).then((x) => (stateData.AllSysGroups = x)),
		other.getSelectList('/api/SysPurchaseRequestBill/GetSysOrgs', [], false).then((x) => (stateData.AllSysOrgs = x)),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => other.setValue(stateData.vmModel, x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
	emit('refresh');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
